<?php
// 为方便系统升级，二次开发中用到的公共函数请写在此文件，禁止修改common.php文件
// ===== 系统升级时此文件永远不会被覆盖 =====

if (!function_exists('unique_order_number')) {
    /**
     * 生成订单号
     *
     * @param [type] $id 唯一因子
     * @return void
     * @Description
     * @author 617 <email：723875993@qq.com>
     */
    function unique_order_number($id = '')
    {
        $timestamp = time();
        $y = date('Ymd', $timestamp);
        $z = date('z', $timestamp);
        $key = str_pad($id, 6, 'X', STR_PAD_LEFT);
        $num = substr_count($key, 'X');
        $ramdom_str = random($num);
        $key = $ramdom_str . $id;
        return $y . $key . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(random(6), 5, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('base64_image_content')) {
    /**
     * 处理base64格式图片存致本地
     * 本地存放位置  /static/upload/日期/文件
     * @param $base64_image_content string base64图片
     * @param $file string 保存的路径
     * @return bool|string 成功返回图片web路劲
     */
    function base64_image_content($base64_image_content, $file, $is_temp = false, $check_size = 0)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            if ($is_temp) {
                $new_file = tempnam(sys_get_temp_dir(), 'k');
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                    $img_content = @file_get_contents($new_file);
                    if ($check_size > 0 && strlen($img_content) > $check_size) {
                        return false;
                    }
                    return $new_file;
                } else {
                    return false;
                }
            }
            $type = $result[2];
            $new_file = ROOT_PATH . $file;
            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0777, true);
            }
            list($msec, $sec) = explode(' ', microtime());
            $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
            $now = $msectime . rand(10000, 99999);
            $new_file = $new_file . $now . ".{$type}";
            $file_dir = $file . $now . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                return $file_dir;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
if (!function_exists('wx_send')) {
    /**
     * 微信请求
     *
     * @param [type] $url
     * @param string $params
     * @return void
     * @Description
     * @author 617 <email：723875993@qq.com>
     */
    function wx_send($url, $params = [], $method = 'GET', $header = array(), $multi = false)
    {
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header
        );
        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url;
                if (!empty($params)) {
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                }
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        if ($error) throw new Exception('请求发生错误：' . $error);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return $error;
        }
    }
}
/**
 * 数组根据指定键值排序
 */
if (!function_exists('array_sort')) {
    function array_sort($array, $key, $sort = SORT_ASC)
    {
        $newArr = array();
        foreach ($array as $k => $v) {
            $newArr[$k][$key] = $v[$key];
        }
        array_multisort($newArr, $sort, $array); //SORT_DESC为降序，SORT_ASC为升序
        return $array;
    }
}

/**
 * 格式化参数格式化成url参数
 * @param $values
 * @return string
 */
if (!function_exists('toUrlParams')) {
    function toUrlParams($values)
    {
        $str = "";
        $i = 0;
        foreach ($values as $k => $v) {
            if (is_array($v)) {
                $v = json_encode($v, 352);
            }
            $v = htmlspecialchars_decode($v);
            $v = str_replace('[]', '', $v);
            if ($i == 0) {
                $str .= "$k" . "=" . "$v";
            } else {
                $str .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        unset($k, $v);
        return $str;
    }
}
/**
 * 检测字符串是否包含ip地址
 */
if (!function_exists('check_ip')) {
    function check_ip($ip)
    {
        $pat = "/(((1?\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((1?\d{1,2})|(2[0-4]\d)|(25[0-5]))/";
        return preg_match($pat, $ip) ? true : false;
    }
}
/**
 * 网络图片转base64
 */
if (!function_exists('interImageToBase64')) {
    function interImageToBase64($image_file, $full = false)
    {
        $options = [
            // 缓存类型为File
            'type'  =>  'File',
            // 缓存有效期为永久有效
            'expire' =>  0,
            //缓存前缀
            'prefix' =>  'poster',
            // 指定缓存目录
            'path'  =>  ROOT_PATH . 'runtime/poster/',
        ];
        cache($options);
        $key = md5($image_file);
        $info = cache($key);
        if ($info) {
            return $info;
        }
        $image_file = str_replace(['\\', 'https'], ['/', 'http'], $image_file);
        $base64_file = '';
        //获取图片的类型
        $suffix = getfilesuffix($image_file);
        if ($suffix != 'unknow') {
            //将图片进行base64编码
            $base64_data = base64_encode(file_get_contents($image_file));
            $base64_file = 'data:' . $suffix . ';base64,' . $base64_data;
            $info = $full ? ['type' => $suffix, 'data' => $base64_file, '_format' => 1] : ['type' => $suffix, 'data' => $base64_data, '_format' => 1];
            cache($key, $info);
            return $info;
        }
        return '';
    }
}

/*
@desc：获取文件真实后缀
@param   name    文件名
@return  suffix  文件后缀
*/
if (!function_exists('getfilesuffix')) {
    function getfilesuffix($name)
    {
        $file = fopen($name, "rb");
        $bin = fread($file, 2); // 只读2字节
        fclose($file);
        $info = @unpack("C2chars", $bin);
        $code = intval($info['chars1'] . $info['chars2']);
        $suffix = "unknow";
        if ($code == 255216) {
            $suffix = "jpg";
        } elseif ($code == 7173) {
            $suffix = "gif";
        } elseif ($code == 13780) {
            $suffix = "png";
        } elseif ($code == 6677) {
            $suffix = "bmp";
        } elseif ($code == 7798) {
            $suffix = "exe";
        } elseif ($code == 7784) {
            $suffix = "midi";
        } elseif ($code == 8297) {
            $suffix = "rar";
        } elseif ($code == 7368) {
            $suffix = "mp3";
        } elseif ($code == 0) {
            $suffix = "mp4";
        } elseif ($code == 8273) {
            $suffix = "wav";
        }
        return $suffix;
    }
}

/**
 * 分词
 *
 * @param [type] $str
 * @return void
 * str 例如：str 清华大学是好学校
 * percentage 例如：0 拉取所有词，1 拉取词的概率为100%。
 * debug 例如：0 关闭调试  1 开启调试
 * @author 617 <email：723875993@qq.com>
 */
if (!function_exists('getStrSplit')) {
    function getStrSplit($str, $percentage = 0.9, $debug = 0)
    {
        $url = "http://api.pullword.com/get.php?source=$str&param1=$percentage&param2=$debug";
        $result = file_get_contents_curl($url);
        if ($result === 'error') return '';
        $result = explode("\n", $result);
        return filter_array($result);
    }
}
/**
 * curl不校验证书请求
 */
if (!function_exists('file_get_contents_curl')) {
    function file_get_contents_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $dxycontent = curl_exec($ch);
        return $dxycontent;
    }
}

if (!function_exists('filter_array')) {
    /**
     * 去除多维数组中的空值
     * @author 
     * @return mixed
     * @param $arr 目标数组
     * @param array $values 去除的值  默认 去除  '',null,false,0,'0',[]
     */
    function filter_array($arr, &$tmp = [])
    {
        if (is_array($arr)) {
            foreach ($arr as $k => $v) {
                $v = trim($v);
                if (empty($v)) {
                    unset($arr[$k]);
                } else if (is_array($v)) {
                    $tmp[$k] = filter_array($v);
                } else {
                    $tmp[$k] = $v;
                }
            }
            $arr = $tmp;
        } else {
            $tmp = $arr;
        }
        return $arr;
    }
}

if (!function_exists('async_http')) {
    /**
     * 优化版多线程请求
     *
     * @param [type] $url_array
     * @param boolean $is_json
     * @param integer $wait_usec
     * @return array
     * @author 617 <email：723875993@qq.com>
     */
    function async_http($url_array, $all_info = false, $key = '', $is_json = true, $wait_usec = 250000)
    {
        if (!is_array($url_array))
            return false;
        $wait_usec = intval($wait_usec);
        $handle = array();
        $active = 0;
        $mh = curl_multi_init();
        $index = 0;
        $i = 0;
        $map = array();
        foreach ($url_array as $url) {
            $ch = curl_init();
            if (isset($url['params'])) {
                $params = $is_json ? json_encode($url['params'], 1) : http_build_query($url['params']);
                //判断是否传输文件
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            }
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts  
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_URL, $url['url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return don't print
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_multi_add_handle($mh, $ch); // 把 curl resource 放进 multi curl handler 里
            $index = $i++;
            $handle[$index] = $ch;
            if (isset($url['params'])) {
                if ($key && isset($url['params'][$key])) {
                    $map[(string) $ch] = $url['params'][$key];
                } else {
                    $map[(string) $ch] = $url['url'] . '[cut]' . http_build_query($url['params']);
                }
            } else {
                $map[(string) $ch] = $url['url'];
            }
        }
        do {
            while (($mrc = curl_multi_exec($mh, $active)) == CURLM_CALL_MULTI_PERFORM);
            if ($mrc != CURLM_OK) {
                break;
            }
            while ($done = curl_multi_info_read($mh)) {
                if ($all_info) {
                    $info = curl_getinfo($done['handle']);
                    $error = curl_error($done['handle']);
                    $results = curl_multi_getcontent($done['handle']);
                    $responses[$map[(string) $done['handle']]] = compact('info', 'error', 'results');
                } else {
                    $responses[] = curl_multi_getcontent($done['handle']);
                }
                curl_multi_remove_handle($mh, $done['handle']);
                curl_close($done['handle']);
            }
            if ($active > 0) {
                curl_multi_select($mh);
            }
        } while ($active);
        curl_multi_close($mh);
        return $responses;
    }
}
